const express = require('express')
const app = express()

// 定义一个用户数组存储注册的用户对象
const userList = [
	{
		username: 'admin',
		password: 123,
	},
]

app.get('/user', (request, response) => {
	console.log('接收请求')
	response.send({
		name: 'jack',
		age: 18,
		message: 'express框架学起来很简单',
	})
})

//名为/login的路由
// 请求参数 用户名和密码
//http://172.21.97.70:3000/login?username='jack'&password=123456
app.get('/login', (request, response) => {
	console.log('username  :', request.query.username + '  password:  ', request.query.password)
	const username = request.query.username
	const password = request.query.password

    const user = userList.find(user=>user.username == username && user.password == password)
	if (user) {
		response.send({
			code: 1,
			message: '登录成功!',
			user: {
				username: username,
				password: password,
			},
		})
	} else {
		response.send({
			code: -1,
			message: '用户名或者密码出错!',
		})
	}
})

/**
 * 注册接口
 *  url: /register
 *  参数: username
 *        password
 *  method: 请求方法
 *        Get
 *  响应:
 * 
 * http://172.21.97.70:3000/register?username=rose&password=123456
 */
app.get('/register', (req, res) => {
	// 1. 接收注册用户名和密码
	const username = req.query.username
	const password = req.query.password

    // 2. 添加注册用户到用户列表
	userList.push({
		username,
		password,
	})

    res.send({
        code:1,
        message: '注册成功'
    })
})

app.listen(3000, () => console.log('监听3000端口,启动服务器成功'))
